package com.atxiaodei.kabudarpc.handler;

import com.atxiaodei.kabudarpc.bean.RpcRequest;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;

/**
 * @ClassName ProcessHandler
 * @Deacription TODO
 * @Author 卡布达
 * @Date 2021/10/31 15:31
 * @Version 1.0
 **/
public class ProcessHandler implements Runnable{

    private Socket socket;

    public ProcessHandler(Socket socket){
        this.socket=socket;
    }
    @Override
    public void run() {
        ObjectInputStream objectInputStream=null;
        ObjectOutputStream objectOutputStream=null;

        try {
            objectInputStream=new ObjectInputStream(socket.getInputStream());

            Object o = objectInputStream.readObject();
            // 拿到对象，进行统一封装，准备反射调用
            RpcRequest rpcRequest=(RpcRequest) o;

            // 去map中拿到实例对象
            Mediator instance = Mediator.getInstance();
            Object process = instance.process(rpcRequest);
            objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            objectOutputStream.writeObject(process);
            objectOutputStream.flush();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
